package com.bmobxiaowa.fragment.photo;

import han.k.base.BaseFragment;
import han.k.common.KLoger;

import java.io.Serializable;
import java.util.List;

import org.simple.eventbus.EventBus;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.bmobxiaowa.R;

/**
 * 
 * Created by hanWG on 2015-11-30 下午3:19:32 $
 * 
 * @Description 进行选择图片的fragment
 *              <p/>
 */
public class PhotoFragment extends BaseFragment {
	// 创建对象 由自己决定
	public static PhotoFragment newInstance(List<PhotoInfo> data) {
		PhotoFragment fragment = new PhotoFragment();
		Bundle bundle = new Bundle();
		bundle.putSerializable("data", (Serializable) data);
		fragment.setArguments(bundle);
		return fragment;
	}

	private GridView gridView;
	private PhotoAdapter photoAdapter;
	private int hasSelect = 1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater
				.inflate(R.layout.fragment_photoselect, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		@SuppressWarnings("unchecked")
		final
		List<PhotoInfo> datas = (List<PhotoInfo>) getArguments()
				.getSerializable("data");
		gridView = (GridView) getView().findViewById(R.id.gridview);
		photoAdapter=new PhotoAdapter(getActivity(), datas, gridView);
		gridView.setAdapter(new PhotoAdapter(getActivity(), datas, gridView));
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(datas.get(position).isChoose()&&hasSelect>1){
					datas.get(position).setChoose(false);
				}else if(hasSelect<10){
					datas.get(position).setChoose(true);
					hasSelect++;
				}else{
					Toast.makeText(getActivity(), "最多选择9张图片！", Toast.LENGTH_SHORT).show();
				}
				photoAdapter.refreshView(position);
				EventBus.getDefault().post(datas,"selectPhoto");
			}
		});
		
	}
	
	
	
	

}
